package com.jds.test.proto;

/**
 * Created by sunyuming on 18/10/16.
 */

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
 * 心跳处理
 * @author lyb
 * 2017年11月27日 下午8:57:55
 */
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state() == IdleState.WRITER_IDLE) {
                System.out.println("* CLIENT WRITER_IDLE send msg heart_beat...");
                sendHeartbeat(ctx);
            } else if (event.state() == IdleState.READER_IDLE) {
                System.out.println("* CLIENT has not receive SERVER msg, so CLOSE\n");
                ctx.close();
            }
        }
    }

    private void sendHeartbeat(final ChannelHandlerContext ctx) {

        MyBaseProto.BaseProto.Builder builder = MyBaseProto.BaseProto.newBuilder();
        builder.setCode(0);
        builder.setMsg("Heartbeat");
        ctx.channel().writeAndFlush(builder.build());
    }
}

